package org.mixed.service;

import lombok.extern.slf4j.Slf4j;
import org.mixed.config.MixProperties;
import org.mixed.core.domain.Constants;
import org.mixed.core.domain.MixNotify;
import org.mixed.core.event.EventAction;
import org.mixed.core.event.MixEvent;
import org.mixed.service.websocket.MagicWebSocketDispatcher;
import org.mixed.service.websocket.WebSocketSessionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class MixApiService {
    @Autowired
    private MixResourceService resourceService;
    @Autowired
    private ApplicationEventPublisher publisher;
    @Autowired
    private MixProperties properties;

    public boolean processNotify(MixNotify magicNotify) {
        if (magicNotify == null || properties.getInstanceId().equals(magicNotify.getFrom())) {
            return false;
        }
        log.debug("收到通知消息:{}", magicNotify);
        switch (magicNotify.getAction()) {
            case WS_C_S:
                return processWebSocketMessageReceived(magicNotify.getClientId(), magicNotify.getContent());
            case WS_S_C:
                return processWebSocketSendMessage(magicNotify.getClientId(), magicNotify.getContent());
            case WS_S_S:
                return processWebSocketEventMessage(magicNotify.getContent());
            case CLEAR:
                publisher.publishEvent(new MixEvent("clear", EventAction.CLEAR, Constants.EVENT_SOURCE_NOTIFY));
        }
        return resourceService.processNotify(magicNotify);
    }

    private boolean processWebSocketSendMessage(String clientId, String content) {
        WebSocketSessionManager.sendByClientId(clientId, content);
        return true;
    }

    private boolean processWebSocketMessageReceived(String clientId, String content) {
        MagicWebSocketDispatcher.processMessageReceived(clientId, content);
        return true;
    }

    private boolean processWebSocketEventMessage(String content) {
        MagicWebSocketDispatcher.processWebSocketEventMessage(content);
        return true;
    }
}
